<template>
    <div class="register-container">
        <BaseHeader></BaseHeader>
        <div class="main">
            <h3>
                {{$t('create_new_account')}}
                <el-tooltip :content="$t('registration_prompt')">
                    <i class="el-icon-question iconClass"></i>
                </el-tooltip>
            </h3>
            <el-form ref="form" :model="form" label-width="350px" :status-icon="true">
                <el-form-item :label="$t('login.wifiSN')" prop="wifiSN" :rules="[{ required: true, message: $t('index_js_notNull')},{ validator:test_wifiSN, trigger:'blur'}]">
                    <el-input v-big v-model="form.wifiSN" :placeholder="$t('login.seeTheDeviceSn')"></el-input>
                    <el-tooltip class="icon-nmi"  placement="right" effect="light">
                        <div slot="content" style="width:200px;">
                            <img src="../../assets/img/wifiMessage.png" alt="" width="100%">
                        </div>
                        <i class="el-icon-question iconClass"></i>
                    </el-tooltip>
                </el-form-item>
                <el-form-item :label="$t('login.loginName')" prop="loginName" :rules="[{ required: true, message: $t('index_js_notNull')},{ validator:test_LoginName, trigger:'blur'}]">
                    <el-input v-model="form.loginName" auto-complete="new-accounts"></el-input>
                </el-form-item>
                <el-form-item :label="$t('login.password')" prop="password" :rules="[{ required: true, message: $t('index_js_notNull')},{validator:test_password,trigger:'blur'}]">
                    <el-input v-model="form.password" type="password" auto-complete="new-password"></el-input>
                </el-form-item>
                <el-form-item :label="$t('login.repwd')" prop="repassword" :rules="[{ required: true, message: $t('index_js_notNull')},{validator:test_repassword,trigger:'blur'}]">
                    <el-input v-model="form.repassword" type="password" auto-complete="new-password"></el-input>
                </el-form-item>
                <el-form-item :label="$t('country')" prop="nation" :rules="[{ required: true, message: $t('index_js_notNull')}]" >
                    <el-select v-model="form.nation" filterable :placeholder="$t('pleaseSelect')">
                        <el-option
                        v-for="item in selectCountryData"
                        :key="item.enName"
                        :label="item.enName"
                        :value="item.enName">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item :label="$t('timeZone')" prop="timeZone" :rules="[{ required: true, message: $t('index_js_notNull')}]">
                    <el-select v-model="form.timeZone" filterable :placeholder="$t('pleaseSelect')" @change="changeTimezone">
                        <el-option
                        v-for="item in selectTimezoneData"
                        :key="item.timeZoneValue"
                        :label="item.timeZone"
                        :value="item.timeZoneValue">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="NMI" prop="nmi" v-if="form.nation=='AUSTRALIA'" :rules="[{ required: form.matchNmi, message: $t('index_js_notNull')},{validator:test_nmi,trigger:'blur'}]">
                    <span slot='label'><el-checkbox v-model="form.matchNmi" @change='changeNmiModal'></el-checkbox> NMI</span>
                    <el-input v-model="form.nmi" placeholder="" :disabled="!form.matchNmi" ></el-input>
                    <el-tooltip class="icon-nmi" placement="top">
                        <div slot="content">
                            The National Metering Identifier (NMI) is a unique 10 or 11 digit number used to identify every electricity network connection point in Australia.
                            <br>You can find your NMI on your electricity bill.
                            <br>
                            If you don’t have an electricity bill handy, you can call your current electricity retailer to ask for your NMI.
                        </div>
                        <i class="el-icon-question iconClass"></i>
                    </el-tooltip>
                    
                </el-form-item>

                <el-form-item :label="$t('site.capacity')" prop="capacity" :rules="[{ required: true, message: $t('index_js_notNull')},{validator:test_capacity,trigger:'blur'}]">
                    <el-input v-model="form.capacity" placeholder=""></el-input>
                </el-form-item>
                <el-form-item :label="$t('login.email')" prop="email" :rules="[{ required: true, message: $t('index_js_notNull')},{validator:test_email,trigger:'blur'}]">
                    <el-input v-model="form.email"></el-input>
                </el-form-item>
                <el-form-item :label="$t('userName')">
                    <el-input v-model="form.userName"></el-input>
                </el-form-item>
                <el-form-item :label="$t('telphone')" prop="phone" :rules="[{validator:test_telphone,trigger:'blur'}]">
                    <el-input v-model="form.phone"></el-input>
                </el-form-item>
                <el-form-item :label="$t('location')" required>
                    <el-input v-model="form.address" v-show="form.address!=''" class="pull-left" style="width:calc(100% - 24px)" readonly></el-input>
                    <i class="iconfont icon-marker-site pull-left icon-marker" @click="showMap()"></i>
                </el-form-item>
                <el-form-item label-width="320px" class="small" v-show="checkVisible">
                    <el-checkbox v-model="ifSummerTime" true-label="1" false-label="0" @change="changeSummer">{{$t('index.summerTimmer')}}</el-checkbox>
                </el-form-item>
                <el-form-item label-width="320px" class="small">
                    <el-checkbox v-model="form.visiable" true-label="1" false-label="0">{{$t('login.isSure2')}}</el-checkbox>
                </el-form-item>
                <el-form-item label-width="320px" class="small">
                    <el-checkbox v-model="form.authorizeFlag" :true-label="1" :false-label="0">{{$t('site.js_isnot_authorize')}}</el-checkbox>
                </el-form-item>
                <el-form-item label-width="320px" class="small a-href">
                    <el-checkbox v-model="form.agreementFlag" true-label="1" false-label="0"></el-checkbox>
                    <el-link class="marginleft_10" @click="()=>{$store.commit('setVisibleInfo',true)}">{{$t('login.isSure')}}</el-link>
                </el-form-item>

            </el-form>
            <el-row class="footer">
                <el-button @click="()=>{$router.push({path:'/login'})}">{{$t('back')}}</el-button>
                <el-button type="primary" @click="save('form')">{{$t('login.signUp')}}</el-button>
            </el-row>
        </div>
        <el-dialog
        :title="$t('add-nmi-code')"
        :visible.sync="dialogVisible"
        width="30%"
        :close-on-click-modal='false'
        >
        <span>{{$t('unbindCode-not-msg')}}</span>
        <el-input v-model="unbindCode" style="width:80%;margin-top:15px;text-align:center;"></el-input>
        <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">{{$t('cancel')}}</el-button>
            <el-button type="primary" @click="spannmiValidateUnbindCode">{{$t('save')}}</el-button>
        </span>
        </el-dialog>
        <agreement></agreement>
        <baseBaiduMapSite :mapData='mapData' :address='form.address' @getPoint='getPoint'></baseBaiduMapSite>
        <baseGoogleMapSite :mapData='mapData' :address='form.address' @getPoint='getPoint'></baseGoogleMapSite>
        <baseSummer @getSummer='getSummer'></baseSummer>
    </div>
</template>

<script>
import BaseHeader from '../../components/baseHeader'
import baseBaiduMapSite from '../../components/map/baseBaiduMapSite'
import baseGoogleMapSite from '../../components/map/baseGoogleMapSite'
import baseSummer from '../../components/common/baseSummer'
import agreement from './agreement'
import md5 from 'js-md5'
import moment from 'moment'
export default {
    components: {
        BaseHeader,
        baseBaiduMapSite,
        baseGoogleMapSite,
        agreement,
        baseSummer
    },
    data() {
        this.test_wifiSN = async(rule, value, callback) => {
            let res = await this.API.registerCheckWifi({wifiSn:this.form.wifiSN})
            if (res == '2') {
                callback(new Error(this.$t('login.js_sign_wifisn_error')));
            }else if (res == '3') {
                callback(new Error(this.$t('login.js_sign_wifisn_registered')));
            }else if (res == '4') {
                callback(new Error('other error'));
            }else{
                callback();
            }
        }
        this.test_LoginName = async(rule, value, callback) => {
            let res = await this.API.registerCheckLoginName({username:this.form.loginName})
            if (res == '1') {
                callback(new Error(this.$t('login.js_sign_userName_exist')));
            }else if (res == '4') {
                callback(new Error('other error'));
            }else{
                callback();
            }
        }
        this.test_nmi = async(rule, value, callback) => {
            let res = await this.API.siteCheckNmi({nmi:this.form.nmi})
            if (res.object == '1') {
                callback(new Error(this.$t('NMI.importModalMsg1G')));
            }else{
                callback();
            }
        }
        this.test_capacity = async(rule, value, callback) => {
            if(!this.Regs.num_reg.test(value)){
                callback(new Error(this.$t('site.js_capacity_rule')));
            }else{
                callback();
            }
        }
        this.test_zero = async(rule, value, callback) => {
            if(value==='请选择'){
                callback(new Error(this.$t('pleaseSelect')));
            }else{
                callback();
            }
        }
        this.test_password = (rule, value, callback) => {
            if(this.Regs.space_reg.test(value)){
                callback(new Error(this.$t('pwd_contain_space')));
            }else{
                callback()
            }
        }
        this.test_repassword = (rule, value, callback) => {
            if(value!=this.form.password){
                callback(new Error(this.$t('login.js_sign_repwd_error')));
            }else{
                callback()
            }
        }
        this.test_telphone = (rule, value, callback) => {
            if(value!=''&&!this.Regs.phone_reg.test(value)){
                callback(new Error(this.$t('login.js_sign_phone_error')));
            }else{
                callback()
            }
        }
        this.test_email = (rule, value, callback) => {
            if(value!=''&&!this.Regs.email_reg.test(value)){
                callback(new Error(this.$t('login.js_sign_email_error')));
            }else{
                callback()
            }
        }
        return {
            dialogVisible:false,
            mapType:localStorage.getItem('mapType'),
            agreeResData:{},
            form:{
                siteName:'',
                nation:'',
                timeZone:'',
                wifiSN:'',
                loginName:'',
                capacity:'',
                // siteOwn:'',
                // packageId:'',
                // postcode:'',
                province:'',
                city:'',
                county:'',
                // town:'',
                address:'',
                longitude:'',
                latitude:'',
                phone:'',
                summerEndTime:'',
                summerStartTime:'',
                visiable:'1',
                authorizeFlag:1,
                agreementFlag:'0',
                agreeTime:moment().format("YYYY-MM-DD hh:mm:ss"),
                optType:1,
                domain:window.location.host,
                nmi:'',
                matchNmi:true,
            },
            ifSummerTime:false,
            checkVisible:false,
            selectCountryData:[],
            selectTimezoneData:[],
            mapData:{
                width:'100%',
                height:'500px',
                zoom:10,
                center:{
                    lng:116,
                    lat:30
                },
                mapObj:{},//地图对象
                markers:{},//地图上所有的标记
            },
            unbindCode:'',
        };
    },
    computed: {

    },
    watch:{

    },
    beforeCreate(){
        this.UtilsFun.createGoogle()
    },
    mounted(){
        this.selectCountry()
        this.selectTimezone()
        this.getDictionaryBatch()
        if(this.mapType==='2'){
            this.geolocation()
        }
    },
    methods: {
        async spannmiValidateUnbindCode(){
            if(!this.unbindCode){
                this.comm.showMsg(false,this.$t('unbindCode-not-null'))
                return
            }
            let res = await this.API.spannmiValidateUnbindCode({
                unbindCode:this.unbindCode
            })
            if(this.comm.showMsg(res.success)){
                this.dialogVisible = false
                this.form.matchNmi = false
                this.form.nmi = ''
            }else{
                this.form.matchNmi = true
            }
        },
        changeNmiModal(){
            if(!this.form.matchNmi){
                this.dialogVisible = true
                this.form.matchNmi = true
            }
        },
        async getDictionaryBatch(){
            let res = await this.API.getDictionaryBatch({
                dictCodes:'CHINA_DES,SUMMER_TYPE,MONTH,SORT_TYPE,WEEK,NOWEEK',
                lang:localStorage.getItem('lang')
            })
            this.summerTimeData=res
        },
        async selectCountry(){
            let res = await this.API.selectCountry()
            this.selectCountryData = res || []
            if(localStorage.getItem('mapType')==1){
                this.form.nation='中国'
            }
        },
        async selectTimezone(){
            let res = await this.API.getTimeZoneList()
            this.selectTimezoneData = res || []
            let timezoneId=Intl.DateTimeFormat().resolvedOptions().timeZone
            this.selectTimezoneData.forEach(item=>{
                if(timezoneId==item.timeZoneId){
                    this.form.timeZone=item.timeZoneValue
                    this.changeTimezone(item.timeZoneValue)
                }
            })
        },
        async changeTimezone(val){
            console.log(val,'changeTimezone')
            let res = await this.API.getSummerTime({timeZoneValue:val})
            if(res.summerStartTime!=null && res.summerStartTime.indexOf(';')!=-1 && res.summerEndTime!=null && res.summerEndTime.indexOf(';')!=-1){
                // this.ifSummerTime=true
                var startArray=res.summerStartTime.split(';')
                var endArray=res.summerEndTime.split(';')
                if(startArray.length>2 && endArray.length>2){//按星期
                    this.summerType='1'
                    this.summer_form1={
                        start_summerMonth: startArray[0],
                        start_summerSort: startArray[1]>0?'1':'2',
                        start_summerNum: Math.abs(startArray[1]),
                        start_summerWeek: startArray[2],
                        start_summer_hour: startArray[3],
                        end_summerMonth: endArray[0],
                        end_summerSort: endArray[1]>0?'1':'2',
                        end_summerNum: Math.abs(endArray[1]),
                        end_summerWeek: endArray[2],
                        end_summer_hour: endArray[3],
                    }
                    this.ifSummerTime=true
                }
                this.checkVisible=false
                this.form.summerStartTime=res.summerStartTime
                this.form.summerEndTime=res.summerEndTime
                console.log(this.form,'form timezone')
            }else{
                this.checkVisible=true
                this.ifSummerTime=false
                for(let item in this.summer_form1){
                    this.summer_form1[item]=item=='start_summer_hour'||item=='end_summer_hour'?'00:00':''
                }
            }
        },
        changeSummer(val){
            if(val=='1'){
                this.$store.commit('setVisibleSummer',true)
            }
        },
        save(formName){
            console.log(this.city)
            this.$refs[formName].validate((valid) => {
              if (valid) {
                  let flag=true
                  
                  if(this.form.longitude==''||this.form.longitude==null){
                      this.$message.error(this.$t('map_validateLatLng'))
                      flag=false
                      return
                  }
                  if(this.form.address==''||this.form.address==null){
                      this.$message.error(this.$t('login.js_sign_address'))
                      flag=false
                      return
                  }
                  if(this.form.agreementFlag==0){
                      this.$message.error(this.$t('selection_protocol'))
                      flag=false
                      return
                  }

                  if(flag){
                      this.commitForm()
                  }
              } else {
                console.log('error submit!!');
                return false;
              }
            });
        },
        async commitForm(){
            delete this.form.repassword
            let pointType=localStorage.getItem('mapType')==1?'B':'G'
            this.$set(this.form,'latitude',pointType+this.form.latitude)
            this.$set(this.form,'longitude',pointType+this.form.longitude)

            this.form.siteName=this.form.loginName+this.$t('regsterSite.siteSuffix')
            let res = await this.API.registerUser(
                Object.assign(this.form,{
                    password:md5(this.form.password),
                    unbindCode:this.unbindCode
                })
            )
            if(res.success){
                this.$confirm('Welcome to SolaX Cloud', {
                    iconClass:'el-icon-success',
                    customClass:'message-register',
                    confirmButtonText: this.$t('login'),
                    cancelButtonText: this.$t('close'),
                    center: true
                }).then(() => {
                    this.loginin()
                }).catch(() => {
                    this.$router.push({path:'/login'})        
                });
            }else{
                this.$message.error(this.$t('index.control_fail'));
            }
        },
        //保存定位的经纬度
        savePoint(point){
            this.mapData.center=point
            this.mapData.markers=point
            this.form.longitude=point.lng
            this.form.latitude=point.lat
            console.log(this.form.latitude)
            console.log(this.form.longitude)
        },
        //定位
        geolocation(){
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(
                (position) => {
                    const point = {
                        lat: position.coords.latitude,
                        lng: position.coords.longitude,
                    };
                    this.savePoint(point)
                    this.getAddressByPoint(point)
                },
                () => {
                    console.log('error')
                }
                );
            }
        },
        //地理反解析
        getAddressByPoint(point){
            let that=this
            let isFirst=true
            try{
                //实例化Geocoder服务
                var geocoder = new google.maps.Geocoder();
                geocoder.geocode({ location: new google.maps.LatLng(point.lat, point.lng) }, function geoResults(results, status) {
                    if (status == google.maps.GeocoderStatus.OK) {
                        isFirst=false;
                        that.form.address=results[0].formatted_address
                        console.log(results[0])
                        let short_name=''
                        results.forEach(item=>{
                            if(item.types[0]=='country'){
                                short_name=item.address_components[0].short_name
                            }
                        })
                        // results[0].address_components.forEach(item=>{
                        //     if(item.types[0]=='country'){
                        //         short_name=item.short_name
                        //         console.log(item.short_name,'country')
                        //     }
                        //     if(item.types[0]=='administrative_area_level_1'){
                        //         that.form.province=item.long_name
                        //         console.log(item.long_name,'province')
                        //     }
                        //     if(item.types[0]=='locality'){
                        //         that.form.city=item.long_name
                        //         console.log(item.long_name,'city')
                        //     }
                        //     if(item.types[0]=='political'){
                        //         that.form.county=item.long_name
                        //         console.log(item.long_name,'county')
                        //     }
                        // })
                        console.log(that.form)
                        if(short_name){
                            let time=that.selectCountryData.length>0?0:1000
                            setTimeout(()=>{
                                that.selectCountryData.forEach(item=>{
                                    if(short_name==item.enShort){
                                        that.form.nation=item.enName
                                    }
                                })
                            },time)
                        }
                    }else {
                    }
                });
            }catch(err){
                if(isFirst){
                    console.log('重新定位')
                    setTimeout(function(){
                        that.getAddressByPoint(point)
                    },1000)
                }
            }
        },
        async loginin(){
            let res = await this.API.loginIn({
                username:this.form.loginName,
                userpwd:this.form.password
            })
            if(res){
                let errCode=res.loginCode
                if(res.success){
                if(errCode=='0'){
                    if(this.checked){
                    localStorage.setItem('username',this.username);
                    localStorage.setItem('password',this.password);
                    }
                    sessionStorage.setItem('token',res.token);
        
                    sessionStorage.setItem('loginURL',window.location);//ODM需求保存登录地址
                    sessionStorage.setItem('loginTime',this.$options.filters['dateFormat'](new Date()));
        
                    sessionStorage.setItem('userObj',JSON.stringify(res.user));//保存用户数据
                    localStorage.setItem('userId',res.user.ids);
                    localStorage.setItem('userType',res.user.userType);
        
                    let userType=res.user.userType
                    if(userType!=5){
                    this.$router.push({ path: '/overview_agent' })
                    }else{
                    this.$router.push({ path: '/overview' })
                    }
                }else if(errCode=='6'){
                    this.agreeResData = res
                    this.$store.commit('setVisibleInfo',true)
                } 
                }else{
                if(errCode=='2'){
                    this.errorMsg= this.$t('login.js_none_user');
                }else if(errCode=='3'){
                    this.errorMsg=this.$t('login.js_error_pwd') +res.surplusTimes+this.$t('login.js_error_pwd_numunit');
                }else if(errCode=='4'){
                    this.errorMsg=this.$t('login.js_error_loginTime')
                }else if(errCode=='5'){
                    this.errorMsg=this.$t('login.js_error_id')
                }else if(errCode=='6'){
                    //打开regsterAgreementPlus
                    this.$store.commit('setVisibleInfo',true)
                }else if(errCode=='7'){
                    this.errorMsg=this.$t('login.js_firm_isdeleted')
                }
                }
            }else{
                this.errorMsg=this.$t('service-error-contact-admin')
            }
            },
        //打开地图
        showMap(){
            if(this.mapType==='1'){
                this.$store.commit('setVisibleBaiduMapSite',true)
            }else{
                this.$store.commit('setVisibleGoogleMapSite',true)
            }
        },
        getPoint(point,address){
            this.$set(this.form,'address',address)
            this.$set(this.form,'latitude',point.lat)
            this.$set(this.form,'longitude',point.lng)
            this.mapData.markers=point
            this.mapData.center=point
            console.log(this.form.latitude)
            console.log(this.form.longitude)
        },
        getSummer(data){
            console.log(data)
            this.form.summerStartTime=data.summerStartTime
            this.form.summerEndTime=data.summerEndTime
        }
    }
};
</script>

<style  lang="less">
    .register-container{
        .a-href{
            .el-form-item__content{
                width: 100% !important;
            }
        }
        .main{
            margin-top: 30px;
            margin: 0 auto;
            width: 1000px;
            &>h3{
                text-align: center;
                font-size: 24px;
                .iconClass{
                    margin-top: -3px;
                    font-size: 16px;
                    color: #666;
                    vertical-align: middle;
                }
            }
            .el-form-item--small .el-form-item__content, .el-form-item--small .el-form-item__label {
                width: 350px;
            }
            .el-form-item--mini.el-form-item, .el-form-item--small.el-form-item {
                margin-bottom: 10px;
                &.small{
                    margin-bottom: 0;
                }
            }
            .footer{
                margin:30px 0 10px;
                text-align: center;
                button{
                    padding: 10px 40px;
                }
            }
            .el-link{
                margin-left: 10px;
                line-height: 20px;
            }
            .icon-marker{
                flex: 1;
                text-align: right;
                color: #fd5f5f;
                font-size: 24px;
                cursor:pointer;
            }
            
        }
        .icon-nmi{
            position: absolute;
            top: 10px;
            right: 10px;
            color: #333;
        }
    }
    .el-message-box.message-register {
        display: inline-block;
        width: 300px;
        .el-icon-success{
            font-size: 60px !important;
        }
        font-size: 16px;
        font-weight: bold;
    }
</style>
